<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\api\controller;
use think\Controller;
use think\Db;

class  Weixin extends Base  {
    // 定义配置项
    private $config=array(
        'APPID'              => 'wx9feafce4eccb4728', // 微信支付APPID.
        'MCHID'              => '1582362791', // 微信支付MCHID 商户收款账号  1556016481
        'KEY'                => 'NwyWVrJJX35zMM8nB2PaYPaoMVNssdH3', // 微信支付KEY
        'APPSECRET'          => '81b17ac2628875727b2393c1bb285e05', // 公众帐号secert (公众号支付专用)
        'NOTIFY_URL'         => 'http://test.xuanwumobile.com/api/Weixin/huidiao', // 接收支付状态的连接
    );
    public $body;//描述
    public $total_fee;
    public $out_trade_no;//订单号

    // 构造函数
    public function __construct($config=null){
        // 如果配置项为空 则直接返回
        if (!empty($config)) {
            $this->config=$config;
        }
    }
    
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }
    
    /**
     * 生成订单
     * @return \think\response\Json
     * order_id        订单ID
     */
    public function WeChatApi(){

        $params = input('param.');
        $res = $this->checkAll($params['user_id'], $params['time'], $params['value'], $params['reqKey']);
        if($res == 112) {
            return json(['status' => 301, 'msg' => $this->otherLogin]);
        }elseif($res == 110){
            return json(['status' => 302, 'msg' => $this->frost]);
        }
    
        $order = Db::table('up_order')
            ->field('order_num, order_price, order_cate')
            ->where('order_id', $params['order_id'])
            ->find();
        if($order['order_cate'] == 1 || $order['order_cate'] == 2){
            $this->body = '赛事照片购买';
        }elseif($order['order_cate'] == 3 || $order['order_cate'] == 4){
            $this->body = '赛事报名';
        }else{
            $this->body = '图书购买';
        }
        
        $this->total_fee = $order['order_price'] * 100;
//        $this->total_fee = 1;
        $this->out_trade_no = $order['order_num'];
        $order_info = array();
        $order_info['body'] = $this->body; // 描述
        $order_info['total_fee'] = $this->total_fee; // 订单金额
        $order_info['out_trade_no'] = $this->out_trade_no; // 订单号
        $order_info['product_id'] = $order['order_num'] . 'abacadaeafahaj'; // 产品ID
        $order_info['trade_type'] = 'APP'; // 类型
        $respont = $this->WeChatPayReady($order_info);
        return json_encode(['status'=>200, 'msg'=>$respont, 'order_id' => $params['order_id']]);
    }
    
    /**
     * 统一下单
     * @param  array $order 订单 必须包含支付所需要的参数 body(产品描述)、total_fee(订单喵额)、out_trade_no(订单号)、product_id(产品id)、trade_type(类型：JSAPI，NATIVE，APP)
     */
    public function WeChatPayReady($order,$type=null){
        // 获取配置项
        $weixinpay_config=$this->config;
        $config=array(
            'appid'=>$weixinpay_config['APPID'],
            'mch_id'=>$weixinpay_config['MCHID'],
            'nonce_str'=>'test',
            'spbill_create_ip'=>$_SERVER['REMOTE_ADDR'],
            'notify_url'=>$weixinpay_config['NOTIFY_URL']
        );
        if(!empty($type)){
            $config['notify_url']='http://test.xuanwumobile.com/api/Weixin/huidiao';
        }
        // 合并配置数据和订单数据
        $data=array_merge($order,$config);

        // 生成签名
        $sign=$this->makeSign($data);
        $data['sign']=$sign;
        $xml=$this->toXml($data);
        $url = 'https://api.mch.weixin.qq.com/pay/unifiedorder';//接收xml数据的文件
        $header[] = "Content-type: text/xml";//定义content-type为xml,注意是数组
        $ch = curl_init ($url);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);//严格校验
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $response = curl_exec($ch);
        if(curl_errno($ch)){
            print curl_error($ch);
        }
        curl_close($ch);
        $result=$this->toArray($response);
        $result['sign']=$sign;
        $result['nonce_str']='test';
        $result2 = $this->getOrder($result['prepay_id']);
        return $result2;
    }
    
    /**
     * 获取时间
     * @return array
     */
    public function getDateBytimeDate($string){
        $replacement = '-';
        $replacement2 = ':';
        $a = substr_replace($string, $replacement, 4, 0);
        $b = substr_replace($a, $replacement, 7, 0);
        $c = substr_replace($b, ' ', 10, 0);
        $d = substr_replace($c, $replacement2, 13, 0);
        $e = substr_replace($d, $replacement2, 16, 0);
        return $e;
    }
    
    /**
     * 回调
     * @return string
     */
    public function write_admin_log($data)
    {
        $file_name = ROOT_PATH . '/public/log/' . date('Ymd', time()) . '.txt';
        if (is_array($data)) {
            $data_str = json_encode($data, true);
        } else {
            $data_str = $data;
        }
        file_put_contents($file_name, $data_str . "\r\n\r\n", FILE_APPEND);
    }
    
    /**
     * 验证
     * @return array 返回数组格式的notify数据
     */
    public function huidiao(){
        // 获取xml
        $xml=file_get_contents('php://input', 'r');
        // 转成php数组
        $getInfo=$this->toArray($xml);
//        $this->write_admin_log($getInfo);
        // 保存原sign
        $data_sign=$getInfo['sign'];
        // sign不参与签名
        unset($getInfo['sign']);
        $sign=$this->makeSign($getInfo);
        // 判断签名是否正确  判断支付状态
        if ($sign===$data_sign && $getInfo['return_code']=='SUCCESS' && $getInfo['result_code']=='SUCCESS') {
    
            $num = $getInfo['out_trade_no']; // 订单号
            $order = Db::table('up_order')
                ->where('order_num', $num)
                ->field('order_user_id, order_id, order_cate, order_match_id, order_status, 
                    order_type, order_image_id')
                ->find();
            $match = Db::table('up_match')
                ->where('match_id', $order['order_match_id'])
                ->field('match_cate')
                ->find();
            if($order['order_status'] == 1){
                Db::startTrans();
                try{
                    if($order['order_cate'] == 3 || $order['order_cate'] == 4){ // 赛事
                        // 修改报名信息状态
                        Db::table('up_match_apply_info')
                            ->where('ma_order_num', $num)
                            ->setField('ma_apply_status', 2);
        
                        // 修改赛事报名人数  up_match_apply_group
                        if($match['match_cate'] == 1){ // 帆船
                            $apply = Db::table('up_match_apply_info')
                                ->where('ma_user_id', $order['order_user_id'])
                                ->where('ma_match_id', $order['order_match_id'])
                                ->field('ma_group')
                                ->find();
                            Db::table('up_match_apply_group')
                                ->where('mag_match_id', $order['order_match_id'])
                                ->where('mag_group_id', $apply['ma_group'])
                                ->setInc('mag_already_num');
                        }else{
                            // 按组别分组
                            $apply = Db::table('up_match_apply_info')
                                ->field('count(ma_group) group_num, ma_group')
                                ->where('ma_role', 1)
                                ->where('ma_order_num', $num)
                                ->group('ma_group')
                                ->select();
                            foreach($apply as $kk => $vv){
                                Db::table('up_match_apply_group')
                                    ->where('mag_match_id', $order['order_match_id'])
                                    ->where('mag_group_id', $vv['ma_group'])
                                    ->setInc('mag_already_num', $vv['group_num']);
                            }
                        }
        
                    }elseif($order['order_cate'] == 1 || $order['order_cate'] == 2){ // 照片
                        // 插入我购买的照片  up_my_pay_images
                        $images = [];
                        $img = explode(',', $order['order_image_id']);
                        foreach($img as $k => $v){
                            $images[$k] = [
                                'mpi_user_id' => $order['order_user_id'],
                                'mpi_image_id' => $v
                            ];
                        }
                        Db::table('up_my_pay_images')->insertAll($images);
                    }else{ // 图书
        
                    }
    
                    // 修改订单信息
                    Db::table('up_order')
                        ->where('order_id', $order['order_id'])
                        ->update([
                            'order_status' => 2,
                            'order_pay_time' => date('Y-m-d H:i:s')
                        ]);
    
                    // 代付需要发送系统消息
                    if($order['order_type'] == 4){
                        $notice = [
                            'notice_title' => '支付通知',
                            'notice_content' => '您发送的代付订单“' . $num . '”已经被支付成功。',
                            'notice_range' => 2,
                            'notice_user' => ',0,' . $order['order_user_id'] . ',',
                            'notice_read_user' => ',0,',
                            'notice_del_user' => ',0,',
                            'notice_type' => 2,
                            'notice_committee_id' => 0,
                            'notice_time' => date('Y-m-d H:i:s')
                        ];
                        Db::table('up_notice')->insert($notice);
                    }
        
                    Db::commit();
                    $result = true;
                }catch(\Exception $e){
                    Db::rollback();
                    $result = false;
                }
            }else{
                $result = true;
            }
        } else{
            $result = false;
        }
        // 返回状态给微信服务器----------------
        if ($result) {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
        exit();
        return $result;
    }
    
    /**
     * 生成签名
     * @return 签名，本函数不覆盖sign成员变量，如要设置签名需要调用SetSign方法赋值
     */
    public function makeSign($data){
        // 去空
        $data=array_filter($data);
        //签名步骤一：按字典序排序参数
        ksort($data);
        $string_a=http_build_query($data);
        $string_a=urldecode($string_a);
        //签名步骤二：在string后加入KEY
        $config=$this->config;
        $string_sign_temp=$string_a."&key=".$config['KEY'];
        //签名步骤三：MD5加密
        $sign = md5($string_sign_temp);
        // 签名步骤四：所有字符转为大写
        $result=strtoupper($sign);
        return $result;
    }

    /**
     * 将xml转为array
     * @param  string $xml xml字符串
     * @return array       转换得到的数组
     */
    public function toArray($xml){
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $result= json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $result;
    }
    
    /**
     * 输出xml字符
     * @throws WxPayException
     **/
    public function toXml($data){
        //var_dump($data);
        if(!is_array($data) || count($data) <= 0){
            //throw new WxPayException("数组数据异常！");
        }
        $xml = "<xml>";
        foreach ($data as $key=>$val){
            if (is_numeric($val)){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }
    
    //数组转xml
    function arrayToXml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key=>$val)
        {
            if (is_numeric($val))
            {
                $xml.="<".$key.">".$val."</".$key.">";

            }
            else
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
        }
        $xml.="</xml>";
        return $xml;
    }

    //post https请求，CURLOPT_POSTFIELDS xml格式
    public function postXmlCurl($xml,$url,$second=30)
    {
        //初始化curl
        $ch = curl_init();
        //超时时间
        curl_setopt($ch,CURLOPT_TIMEOUT,$second);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        //返回结果
        if($data)
        {
            curl_close($ch);
            return $data;
        }
        else
        {
            $error = curl_errno($ch);
            echo "curl出错，错误码:$error"."<br>";
            echo "<a href='http://curl.haxx.se/libcurl/c/libcurl-errors.html'>错误原因查询</a></br>";
            curl_close($ch);
            return false;
        }
    }
    
    //获取指定长度的随机字符串
    function getRandChar($length){
        $str = null;
        $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
        $max = strlen($strPol)-1;

        for($i=0;$i<$length;$i++){
            $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
        }

        return $str;
    }
    
    //执行第二次签名，才能返回给客户端使用
    public function getOrder($prepayId){
        $data["appid"] = $this->config["APPID"];
        $data["noncestr"] = $this->getRandChar(32);
        $data["package"] = "Sign=WXPay";
        $data["partnerid"] = $this->config['MCHID'];
        $data["prepayid"] = $prepayId;
        $data["timestamp"] = time();
        $s = $this->makeSign($data, false);
        $data["sign"] = $s;
        
        return $data;
    }
    
    /**
     * 获取当前服务器IP
     * @return string
     */
    public  function get_client_ip()
    {
        if ($_SERVER['REMOTE_ADDR']) {
            $cip = $_SERVER['REMOTE_ADDR'];
        } elseif (getenv("REMOTE_ADDR")) {
            $cip = getenv("REMOTE_ADDR");
        } elseif (getenv("HTTP_CLIENT_IP")) {
            $cip = getenv("HTTP_CLIENT_IP");
        } else {
            $cip = "unknown";
        }
        return $cip;
    }
    


}